<template>
  <div class="page-container">
    <VerticalTabNav :vehicleId="vehicleIdFromRoute" />
    
    <div class="bridge-health-container">
      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
          <span class="title">运输路线</span>
          <!-- <el-select
            v-model="currentPageValue"
            class="page-selector"
            @change="handlePageChange"
          >
            <el-option
              v-for="item in pageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :class="{ 'is-active': item.value === currentPageValue }"
            />
          </el-select> -->
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAdd" class="custom-button">
            <i class="el-icon-plus"></i> 新增数据
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        class="custom-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="transportId" label="危化品名称" min-width="120">
          <template #default="{ row }">
            <span class="transport-name">
              {{ transportOptions.find((item) => String(item.value) === String(row.transportId))?.label || row.transportId }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lon" label="经度" width="120">
          <template #default="{ row }">
            {{ Number(row.lon).toFixed(6) }}
          </template>
        </el-table-column>
        <el-table-column prop="lat" label="纬度" width="120">
          <template #default="{ row }">
            {{ Number(row.lat).toFixed(6) }}
          </template>
        </el-table-column>
        <el-table-column prop="routeTime" label="路线时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.routeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="120" align="center">
          <template #default="scope">
            <span class="ellipsis-text" @click="showRemarks(scope.row)">
              {{ (scope.row.remarks || "暂无备注").slice(0, 20) }}
              {{ scope.row.remarks?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)" class="operation-button">
              详情
            </el-button>
            <el-button link @click="handleDelete(row)" class="operation-button danger">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        class="custom-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="选择运输任务" prop="transportId">
            <el-select v-model="form.transportId" placeholder="请选择运输任务" style="width: 100%">
              <el-option
                v-for="item in transportOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="经度" prop="lon">
            <el-input-number
              v-model="form.lon"
              :precision="6"
              :step="0.000001"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="lat">
            <el-input-number
              v-model="form.lat"
              :precision="6"
              :step="0.000001"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="路线时间" prop="routeTime">
            <el-date-picker
              v-model="form.routeTime"
              type="datetime"
              placeholder="选择路线时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注信息" prop="remarks">
            <el-input
              type="textarea"
              v-model="form.remarks"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 备注信息弹窗 -->
      <el-dialog v-model="remarksDialogVisible" title="备注信息" width="40%">
        <div style="white-space: pre-wrap">{{ currentRemarks }}</div>
        <template #footer>
          <span>
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import VerticalTabNav from '@/views/Bridge/basic-data/components/VerticalTabNav.vue';
import { getDangerousGoodsTransportInfo } from "@/api/bridge/bisc/car";
import { 
  getTransportRouteList, 
  getTransportRouteById, 
  addTransportRoute, 
  updateTransportRoute, 
  deleteTransportRoute 
} from "@/api/bridge/bisc/gps";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 获取路由参数
const router = useRouter();
const route = useRoute();
const vehicleIdFromRoute = ref<string | null>(null);

// 页面选择相关
const currentPageValue = ref('route');
const pageOptions = ref([
  { label: '车辆定位', value: 'location' },
  { label: '运输信息', value: 'transport' },
  { label: '运输路线', value: 'route' }
]);

// 页面跳转处理
const handlePageChange = (value: string) => {
  // 保持当前的vehicleId参数
  const query = vehicleIdFromRoute.value ? { vehicleId: vehicleIdFromRoute.value } : {};
  
  if (value === 'transport') {
    router.push({ path: '/basic-data/two-pages/car' });
  } else if (value === 'location') {
    router.push({ path: '/basic-data/three-pages/car-location' });
  } else if (value === 'route') {
    router.push({ path: '/basic-data/four-pages/car-route' });
  }
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  transportId: "",
  lon: 0,
  lat: 0,
  routeTime: "",
  remarks: "",
});

// 备注弹窗相关
const remarksDialogVisible = ref(false);
const currentRemarks = ref("");

// 运输任务列表相关
const transportOptions = ref([]);

// 表单校验规则
const rules = {
  transportId: [{ required: true, message: "请选择运输任务", trigger: "change" }],
  lon: [{ required: true, message: "请输入经度", trigger: "blur" }],
  lat: [{ required: true, message: "请输入纬度", trigger: "blur" }],
  routeTime: [{ required: true, message: "请选择路线时间", trigger: "change" }],
};

// 格式化日期时间
const formatDateTime = (date: string | number | Date) => {
  if (!date) return '-';
  
  // 如果是时间戳字符串，先转换为数字
  if (typeof date === 'string' && /^\d+$/.test(date)) {
    return dayjs(parseInt(date)).format('YYYY-MM-DD HH:mm:ss');
  }
  
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    };
    
    // 如果有车辆ID参数，添加到查询条件
    if (vehicleIdFromRoute.value) {
      params.vehicleId = vehicleIdFromRoute.value;
    }
    
    // 使用正确的API调用
    const res = await getTransportRouteList(params);
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增路线数据";
  const currentTimestamp =new Date();  // 获取当前时间的时间戳
  form.value = {
    id: "",
    transportId: "",
    lon: 0,
    lat: 0,
    routeTime: currentTimestamp.toString(), // 直接使用当前时间戳
    remarks: "",
  };
  dialogVisible.value = true;
};

// 处理查看
const handleView = async (row: any) => {
  try {
    const res = await getTransportRouteById(row.id);
    dialogTitle.value = "查看详情";
    // 确保时间字段正确显示
    const data = { ...res.data };
    // 如果 routeTime 是时间戳字符串，转换为日期对象以便在表单中正确显示
    if (data.routeTime && /^\d+$/.test(data.routeTime)) {
      // 使用 dayjs 创建日期对象
      data.routeTime = dayjs(parseInt(data.routeTime)).format('YYYY-MM-DD HH:mm:ss');
    }
    form.value = data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该条数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteTransportRoute(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  });
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let timestamp;
        // 检查是否已经是时间戳格式
        if (typeof form.value.routeTime === 'string' && /^\d+$/.test(form.value.routeTime)) {
          timestamp = form.value.routeTime; // 已经是时间戳字符串，直接使用
        } else {
          // 否则，将其转换为时间戳
          timestamp = dayjs(form.value.routeTime).valueOf().toString();
        }
        
        const submitData = {
          ...form.value,
          routeTime: timestamp
        };
        
        if (form.value.id) {
          await updateTransportRoute(submitData);
          ElMessage.success("修改成功");
        } else {
          await addTransportRoute(submitData);
          ElMessage.success("新增成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 显示备注信息
const showRemarks = (row: any) => {
  currentRemarks.value = row.remarks || "暂无备注";
  remarksDialogVisible.value = true;
};

// 表格选择改变
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 100000000,
})

// 获取运输任务列表数据
const getTransportOptions = async () => {
  try {
    const res = await getDangerousGoodsTransportInfo(queryParams.value);
    transportOptions.value = res.rows.map((item) => ({
      value: item.id,
      label: item.hazardousMaterial || '未知运输任务',
    }));
  } catch (error) {
    console.error("获取运输任务列表失败:", error);
    ElMessage.error("获取运输任务列表失败");
  }
};

onMounted(() => {
  // 初始化时获取路由参数
  if (route.query.vehicleId) {
    vehicleIdFromRoute.value = route.query.vehicleId as string;
  }
  
  getTransportOptions();
  getList();
});
// 监听路由参数变化
watch(
  () => route.query.vehicleId,
  (newVal) => {
    if (newVal) {
      vehicleIdFromRoute.value = newVal as string;
    } else {
      vehicleIdFromRoute.value = null;
    }
    getList();
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.bridge-health-container {
  flex: 1;
  padding: 20px;
  overflow: auto;

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background: var(--el-bg-color-overlay);
    padding: 16px;
    border-radius: 4px;

    .left {
      .page-selector {
        width: 180px;
        
        :deep(.el-input__wrapper) {
          background-color: transparent;
          box-shadow: none !important;
          
          &:hover {
            background-color: var(--el-fill-color-light);
          }
        }

        :deep(.el-input__inner) {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-color-primary);
        }

        :deep(.el-select-dropdown__item) {
          &.is-active {
            color: var(--el-color-primary);
            font-weight: bold;
            background-color: var(--el-color-primary-light-9);
          }

          &:hover {
            background-color: var(--el-color-primary-light-9);
          }
        }
      }
    }

    .custom-button {
      margin-left: 10px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-bg-color-overlay);

    :deep(th) {
      background: var(--el-bg-color-page) !important;
    }

    :deep(.el-table__row) {
      background-color: var(--el-bg-color-overlay);
    }

    .transport-name {
      color: var(--el-color-primary);
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }

    .operation-button {
      padding: 0 10px;
      font-size: 14px;

      &.danger {
        color: var(--el-color-danger);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

.ellipsis-text {
  cursor: pointer;
  color: var(--el-color-primary);
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    text-decoration: underline;
    opacity: 0.8;
  }
}
</style> 